<?php

namespace App\Modules\Apicrzs\Services\Water;

use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Admin\Entities\Property\WaterCouponModel;
use App\Modules\Admin\Entities\Water\WaterCardTransactionModel;
use App\Modules\Admin\Entities\Water\WaterOrderModel;
use App\Modules\Apicrzs\Entities\UserScoreModel;
use App\Modules\Apicrzs\Entities\UserWaterCardModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Modules\Apicrzs\Services\WeChat\WechatPayService;
use App\Traits\CryptAES;
use Illuminate\Support\Facades\Config;
use function Symfony\Component\String\u;

class PayRechargeService extends BaseServices
{

    public function __construct(WaterOrderModel $model)
    {
        $token = \request()->header('token');
        $user_info = CryptAES::decryptToken($token, 'user_grzq');
        $this->user_id = $user_info['data']['user_id'] ?? 0;
        $this->model = $model;
        $this->userScoreModel = new UserScoreModel();
    }

    public function getLists($params)
    {
        $model = $this->model->with(['coupon_info'])->where(['user_id'=>$this->user_id,'status'=>1]);

        $lists = $model->orderBy($this->model->getKeyName(), 'DESC')
            ->select(['order_id','coupon_id','type','card_no','amount','remark','created_time'])
            ->paginate($this->getLimit($params['limit'] ?? 10));
        return [
            'current_page' => $lists->currentPage(),
            'per_page'     => $lists->perPage(),
            'count_page'   => $lists->lastPage(),
            'total'        => $lists->total(),
            'data'         => $lists->items(),
        ];
    }
    /**
     *  套餐充值 生成订单
     * @param array $params
     * @return array|mixed[]
     */
    public function createRechargeOrder(array $params)
    {
        $openid = $params['openid'] ?? "";
        $card_no = $params['card_no']??"";
        if (!$card_no){
            $this->error='卡号不能为空';
            return false;
        }
        $coupon_id = $params['coupon_id'];
        $amount = $params['amount'] ?? 0;

        $coupon_info = WaterCouponModel::getInstance()->where(['coupon_id' => $coupon_id])->first();

        // 获取带锁的最新数据
        $card_info = UserCardModel::getInstance()->where(['card_code'=>$card_no])->first();
        if (!$card_info){
            $this->error='卡号无效';
            return false;
        }
        $freshCard = UserCardModel::lockForUpdate()->where(['card_code'=>$card_no])->first();

        $valueBefore = $freshCard['remaining_value']??0;
        $valueAfter = $valueBefore + $amount;

        $order_no = $this->model->findAvailableNo();
        $description = "套餐充值【" . $coupon_info['coupon_title'] . "】";
        $order_insert = [
            'user_card_id' => $freshCard['user_card_id'] ?? 0,
            'openid' => $openid,
            'user_id' => $this->user_id,
            'card_no' => $card_no,
            'coupon_id' => $coupon_id,
            'order_sn' => $order_no,
            'type' => $params['type'],
            'value_before' => $valueBefore,
            'value_after' => $valueAfter,
            'amount' => $amount,
            'total_price' => $coupon_info['give_money'],
            'give_price' => ($coupon_info['give_money']-$amount),
            'payment_method' => $params['payment_method'] ?? '',
            'usage_type' => $params['usage_type'] ?? '',
            'paid' => 1,
            'operator_name' => $this->user_id ?? "",
            'remark' => $params['remark'] ?? $description
        ];

        $transaction = parent::create($order_insert);

        $pay_param['openid'] = $openid;
        $pay_param['amount'] = $amount;
        $pay_param['order_sn'] = $order_no;
        $pay_param['description'] = $description;
        $pay_param['attach'] = ['type'=>"water_recharge"];
        $pay_service = new WechatPayService();
        $pay_config = $pay_service->wx_pay('recharge', $pay_param);
        $pay_config['order_sn'] = $order_no;
        if(isset($config['code'])){
            $this->error=$pay_config['msg'];
            return false;
        }
        return $pay_config;
    }


}
